﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

using Code.Models;
using Code.BLL;
using QianBuo.Lottery.Web.Models;
using QianBuo.Lottery.Web.Models.User;
using Code.Commen;
using QianBuo.Lottery.Web.Models.Surrogate;
using QianBuo.Lottery.Web.Models.Account;
using QianBuo.Lottery.Web.Areas.Manage.Models.User;
using QianBuo.Lottery.Web.Commen;
using QianBuo.Lottery.Web.Controllers;
using System.Web.Security;
using System.Text.RegularExpressions;
using System.Security.Principal;
using System.Security.Cryptography;
using QianBuo.Lottery.Web.Areas.Manage.Models.Lottery;

namespace QianBuo.Lottery.Web.Areas.Manage.Controllers
{
    public class UserController : BaseController
    {
        #region 新增用户
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult Rank()
        {
            var BM = new RankManager();
            var model = new RankModel
            {
                Types = BM.Select(s => s.Select(p => new RankItem { id = p.Id, ran = p.Ranks, exper = p.Exper, resetMoneyToMy = Convert.ToDouble(p.ResetMoneyToMy), resetMoneyToUp = Convert.ToDouble(p.ResetMoneyToUp) }).ToArray())
            };

            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult AddRank(int? id, bool? n)
        {
            var BM = new RankManager();

            var model = new RanEditModel { N = n ?? false, ID = id };
            if (!model.N)
            {
                if (!model.ID.HasValue)
                    return RedirectToAction("Rank");
                var item = BM.Select(s => s.FirstOrDefault(p => p.Id == model.ID));
                if (item == null)
                    return RedirectToAction("Rank");
                model.Ranks = item.Ranks;
                model.Exper = item.Exper;
                model.ResetMoneyToMy = Convert.ToDouble(item.ResetMoneyToMy);
                model.ResetMoneyToUp = Convert.ToDouble(item.ResetMoneyToUp);
            }

            return View(model);
        }

       
        [HttpPost]
        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult AddRank(RanEditModel model)
        {
            var rans = new Rank();

            if (!model.N && !model.ID.HasValue)
                return RedirectToAction("Rank");

            if (ModelState.IsValid)
            {
                var BM = new RankManager();
                int rs = 0;
                if (model.N)
                {
                    if (BM.SelectRank().Ranks == model.Ranks)
                    {
                        return Content(Url.Action("Rank").Redirect("等级不能等于当前最大等级！"));
                    }
                    else if (model.Ranks > (BM.SelectRank().Ranks + 1))
                    {
                        return Content(Url.Action("Rank").Redirect("等级必须在当前等级之后一级！"));
                    }
                    else
                    {
                        if (BM.SelectRank().Exper >= model.Exper)
                        {
                            return Content(Url.Action("Rank").Redirect("经验必须高于当前的最高等级的所需经验！"));
                        }
                        else
                        {
                            rs = BM.InsertData(model.Ranks, model.Exper, model.ResetMoneyToMy, model.ResetMoneyToUp);
                        }

                    }
                }
                else
                    rs = BM.Edit(model.ID.Value, model.Ranks, model.Exper, Convert.ToDouble(model.ResetMoneyToMy), Convert.ToDouble(model.ResetMoneyToUp));
                if (rs > 0)
                    return Content(Url.Action("Rank").Redirect("操作成功"));
                else
                    ViewData["msg"] = "操作失败！".AlertOffPage();
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_Lottery_Config")]
        public ActionResult DelRank(int? id)
        {
            if (!id.HasValue)
                return RedirectToAction("Rank");

            var BM = new RankManager();
            int rs = BM.Del(id.Value);
            string msg = "";
            if (rs > 0)
                msg = "删除成功！";
            else
                msg = "删除失败，请检查是否有玩家达到该等级！";
            return Content(Url.Action("Rank").Redirect(msg));

        }


        [Authorize(Roles = "Manager_User_Add")]
        public ActionResult Add()
        {

            var model = new AddUser();
            model.EnableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
            PlayTypeOptionManage PM = new PlayTypeOptionManage();
            model.Options = PM.LoginGetOption_Set(AdminID, 1, null, true).ToArray();
            foreach (var item in model.Options)
            {
                if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false) == false)
                {
                    item.Option.BackMoneyRatio = 0.0;
                }
                item.Option.WinMoneyState = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            }
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            return View(model);
        }

        [HttpPost, Authorize(Roles = "Manager_User_Add")]
        public ActionResult Add(AddUser model)
        {

            int count = 0;
            if (ModelState.Where(p => p.Key.EndsWith(".Option.WinMoney") || p.Key.EndsWith(".Option.BackMoneyRatio")).Any(p => p.Value.Errors.Count > 0))
                ModelState.AddModelError("Error", "奖金返点设置错误，请检查！");
            PlayTypeOptionManage PM = new PlayTypeOptionManage();
            if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
            {
                 int couts = 0;
                foreach (var item in model.Options)
                {
                    if (item.States == false)
                    {
                        couts++;
                    }
                }

                if (couts == model.Options.Count())
                {
                    ViewData["msg"] = Url.Action("Add", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                    return View(model);
                }
            }
            
          


            model.EnableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
          
            if (!ModelState.IsValid == false)
            {
                UserManage um = new UserManage();
                Guid? newUid;
                string msg;
                count = um.AddUser(null, model.LoginName, model.LoginPwd, model.Type, model.EnableAddChildConfig, model.AllChildCount ?? 0, false, true, out newUid, out msg);
                int Insert = PM.InsertUpRank(model.LoginName);
                if (count > 0)
                {
                    //请确保新增用户时已经设置该用户的奖金

                    count = PM.SetOptionByMargin(null, newUid.Value, null, null, model.WinMoneyMargin, 0, true, false);

                    if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true && CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false))
                    {
                        int couts = 0;
                        foreach (var item in model.Options)
                        {
                            if (item.States == false)
                            {
                                couts++;
                            }
                        }

                        if (couts == model.Options.Count())
                        {
                            ViewData["msg"] = Url.Action("Add", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                            return View(model);
                        }
                        List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                        foreach (var item in model.Options)
                        {
                            int winId = item.Option.WinMoneyModelID;
                            int num = 0;
                            foreach (var MyWinId in model.Options)
                            {
                                if (winId == MyWinId.Option.WinMoneyModelID)
                                {
                                    model.Options[num].States = item.States;
                                }
                                num++;
                            }

                        }
                        foreach (var item in model.Options)
                        {
                            Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                            back.BackMoneyRatio = item.Option.BackMoneyRatio;
                            back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                            back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                            var winId = item.Option.WinMoneyModelID;
                            back.States = item.States;
                            list.Add(back);
                        }
                        PM.Updatewin(list,model.LoginName);
                    }

                    if (CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false) == false)
                    {
                      
                        List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                        foreach (var item in model.Options)
                        {
                            int winId = item.Option.WinMoneyModelID;
                            int num = 0;
                            foreach (var MyWinId in model.Options)
                            {
                                if (winId == MyWinId.Option.WinMoneyModelID)
                                {
                                    model.Options[num].States = item.States;
                                }
                                num++;
                            }
                        }

                        if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
                        {


                            int i = 0;
                            foreach (var item in model.Options)
                            {
                                if (item.States == false)
                                {
                                    i++;
                                }
                            }

                            if (i == model.Options.Count())
                            {
                                ViewData["msg"] = Url.Action("Add", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                            }
                            else
                            {
                                foreach (var item in model.Options)
                                {
                                    Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                    back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                    back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                    back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                    var winId = item.Option.WinMoneyModelID;
                                    back.States = item.States;
                                    list.Add(back);
                                }
                            }

                            int result = PM.LoginUpdateOption(list, model.LoginName);
                        }
                        else
                        {
                            foreach (var item in model.Options)
                            {
                                Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                var winId = item.Option.WinMoneyModelID;
                                back.States = true;
                                list.Add(back);
                            }
                            int update = PM.LoginUpdateUserOption(list, model.LoginName);
                        }

                    }
                        if (count < 0)
                            ViewData["msg"] = "<script>if(confirm('新增用户成功!\\r\\n但奖金/反点未设置成功\\r\\n是否现在设置返奖?'))location.href='" + Url.Action("WinMoney", new { uid = newUid, returnUrl = Request.RawUrl }) + "';else location.href='" + Url.Action("Add") + "'</script>";
                        else
                            msg = "新增用户成功!";
                        if (string.IsNullOrEmpty(msg))
                            msg = "操作失败，请稍后再试！";
                }
                if (msg.Length > 15)
                {
                    ModelState.AddModelError("Error", msg);
                    msg = "";
                }
                else
                    msg = Url.Action("Add").Redirect(msg); ;

                ViewData["msg"] = msg;
            }
            else
            {
                model = new AddUser();
                model.EnableAddChildConfig = CacheManage.OptionSite[Option_Site_Key.Site_AddChildConfig_Enable].ToBool(false);
                model.Options = PM.LoginGetOption_Set(AdminID, 1, null, true).ToArray();
                foreach (var item in model.Options)
                {
                    item.Option.BackMoneyRatio = 0.0;
                    item.Option.WinMoneyState = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
                }

            }
           
            return View(model);
        }
        #endregion

        #region 处理提款申请
        [Authorize(Roles = "Manager_Account_TakeMoney")]
        public ActionResult TakeMoneyDetail(TakeMoneys takeMoneys)
        {
            TakeMoneys mondel;
            if (takeMoneys == null)
                mondel = new TakeMoneys();
            else
                mondel = takeMoneys;
            var where = " 1==1 ";
            var paramList = new List<object>();
            GetWhere(mondel.where, out where, out paramList);
            TakeMoneyManage tmm = new TakeMoneyManage();
            var list = tmm.GetTackMoneyList(null, where, paramList.ToArray());
            if (mondel.PageInfo == null)
                mondel.PageInfo = new PageInfo();
            mondel.PageInfo.SunCount = list.Count();
            mondel.TakeMoneyList = list.OrderByDescending(p => p.AddTime).Skip((mondel.PageInfo.CurrPage - 1) * mondel.PageInfo.PageCount).Take(mondel.PageInfo.PageCount).ToArray();
            if (takeMoneys.where.State == (short)TakeMoneyState.UnDispose)
            {
                CacheManage.TakeMoneyUnDisposeCount = mondel.PageInfo.SunCount;
                CacheManage.NewTakeMoneyUnDisposeCount = 0;
            }
            return View(mondel);
        }
        private void GetWhere(TakeMoneys.TackMoeny_Where where, out string str, out List<object> paramList)
        {
            str = " 1==1 ";
            paramList = new List<object>();
            if (where == null)
                return;
            if (where.ID.HasValue)
            {
                str += " and ID=@" + paramList.Count;
                paramList.Add(where.ID.Value);
                return;
            }
            if (where.AddTime_Start.HasValue)
            {
                str += " and AddTime >= @" + paramList.Count;
                paramList.Add(where.AddTime_Start.Value);
            }
            if (where.AddTime_End.HasValue)
            {
                str += " and AddTime < @" + paramList.Count;
                paramList.Add(where.AddTime_End.Value.AddDays(1));
            }
            if (where.Money.HasValue)
            {
                str += " and Money=@" + paramList.Count;
                paramList.Add((decimal)where.Money.Value);
            }
            if (!where.State.HasValue)
                where.State = (short)TakeMoneyState.UnDispose;
            if (where.State.HasValue && where.State.Value != -2)
            {
                str += " and State=@" + paramList.Count;
                paramList.Add(where.State.Value);
            }
        }

        [HttpPost, ActionName("TakeMoneyDetail"), Authorize(Roles = "Manager_Account_TakeMoney")]
        public ActionResult TakeMoneyDetail_Post([Bind(Exclude = "PageInfo")]TakeMoneys model)
        {
            if (ModelState.IsValid)
            {
                return TakeMoneyDetail(model);
            }
            return TakeMoneyDetail(null);
        }

        [Authorize(Roles = "Manager_Account_TakeMoney,Manager_Account_Report")]
        public ActionResult Dispose(Guid id, long tackMoneyID)
        {
            DisposeModel model = new DisposeModel();
            var user = new UserManage().Select(s => s.Where(p => p.ID == id).Select(p => new
            {
                p.ID,
                p.LoginName,
                p.UserType,
                p.RegistTime,
                p.Commands,
                p.CommandID,
                p.Account.Balance,
                p.Person.Name,
                p.Person.BankCardNo,
                p.Person.BankStreet,
                p.Person.QQ,
                p.Person.Phone,
                bankName = p.Person.Bank.Name,
                p.Person.BankCity.Province.ProvinceName,
                p.Person.BankCity.CityName,
                p.Person.PayAccount,
                tackMoney = p.TakeMoney.FirstOrDefault(p1 => p1.ID == tackMoneyID)
            }).FirstOrDefault());
            model.User = new User_Comm
            {
                Uid = user.ID,
                CommandID = user.CommandID,
                Commmands = user.Commands,
                LoginName = user.LoginName,
                RName = user.Name,
                RegistTime = user.RegistTime,
                UserTye = user.UserType
            };
            model.ID = user.tackMoney.ID;
            model.TakeMoney = (double)user.tackMoney.Money;
            model.AddTime = user.tackMoney.AddTime;
            model.Balance = (double)user.Balance;
            model.Remark = user.tackMoney.Remark;
            model.State = (TakeMoneyState)user.tackMoney.State;
            model.BankName = user.bankName;
            model.BankCardNo = user.BankCardNo;
            model.BankProviecs = user.ProvinceName;
            model.CityName = user.CityName;
            model.StreetName = user.BankStreet;
            model.QQ = user.QQ;
            model.Tel = user.Phone;
            model.PayAccount = user.PayAccount;
            model.Type = (BankType)user.tackMoney.BankType;
            model.Account = user.tackMoney.Account;
            model.OperatorName = user.tackMoney.AdminID == null ? null : user.tackMoney.Admin.LoginName;
            return View(model);
        }


        [Authorize(Roles = "Manager_Account_TakeMoney")]

        public JsonResult Dispose_Json(long? id, TakeMoneyState? state, string remark)
        {
            var msg = "";
            var count = -1;
            if (id.HasValue && state.HasValue && state != TakeMoneyState.UnDispose)
            {
                var tmm = new TakeMoneyManage();
                try
                {
                    count = tmm.DisposeTakeMoneyDetail(AdminID, id.Value, state.Value, remark);

                    if (count > 0)
                    {
                        msg = state.Value.GetName();
                        if (CacheManage.TakeMoneyUnDisposeCount > 0)
                            CacheManage.TakeMoneyUnDisposeCount--;
                    }
                    else
                        msg = "操作失败，请稍后重新操作!";
                }
                catch (AppException a)
                {
                    msg = a.Message;
                }
                catch (Exception)
                {
                    msg = "操作失败，请稍后重新操作!";
                }
            }
            return Json(new { msg, count }, JsonRequestBehavior.AllowGet);
        }

        public JsonResult GetTakeMoneyCount()
        {
            return Json(new { count = CacheManage.TakeMoneyUnDisposeCount, voidenable = CacheManage.OptionSite[Option_Site_Key.Site_Sounds_Enable].ToBool(false) }, JsonRequestBehavior.AllowGet);

        }
        public JsonResult GetTakeMoney()
        {
            List<TackMoneys_Mod> models = new List<TackMoneys_Mod>();
            if (CacheManage.NewTakeMoneyUnDisposeCount > 0)
            {
                var count = CacheManage.NewTakeMoneyUnDisposeCount;
                CacheManage.NewTakeMoneyUnDisposeCount = 0;
                var where = " 1==1 ";
                var paramList = new List<object>();
                GetWhere(new TakeMoneys.TackMoeny_Where() { State = (short)TakeMoneyState.UnDispose }, out where, out paramList);
                TakeMoneyManage tmm = new TakeMoneyManage();
                var list = tmm.GetTackMoneyList(null, where, paramList.ToArray()).OrderByDescending(p => p.AddTime).Take(count).ToList();
                models = list;
            }
            return Json(new { list = models.Select(p => new { p.ID, Money = (double)p.Money, p.Remark, Uid = p.User.Uid, name = p.User.LoginName, AddTime = p.AddTime.ToString("yyyy-MM-dd HH:mm:ss") }).ToArray() }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 用户管理
        [Authorize(Roles = "Manager_User_Add,Manager_User_Delete,Manager_User_Edit,Manager_User_WinMoney,Manager_User_Select")]
        public ActionResult AllUser(AllChildModel allChildModel)
        {
            UserManage um = new UserManage();

            AllChildModel model;
            if (allChildModel != null)
            {
                model = allChildModel;
            }
            else
            {
                model = new AllChildModel();
            }
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();
            model.Parents = new List<AllParent_Mod>();
            string where = " 1==1 ";
            List<object> param = new List<object>();
            if (model.Where != null)
                GetWhere(model.Where, out where, out param);
            IEnumerable<AllChild_Mod> allChild = null;
            if (model.Where != null && !string.IsNullOrEmpty(model.Where.ChildName))
            {
                var user = um.Select(s => s.Where(p => p.LoginName == model.Where.ChildName).Select(p => new
                {
                    p.ID,
                    p.CommandID,
                    p.LoginName,
                    p.RegistTime,
                    Balance = p.Account.Balance,
                    p.UserType,
                    LastLoginTime = (DateTime?)p.LoginLog.OrderByDescending(p1 => p1.LoginTime).Select(p1 => p1.LoginTime).FirstOrDefault()
                }).FirstOrDefault());
                if (user == null)
                {
                    ViewData["msg"] = "您查找的用户不存在".AlertOffPage();
                }
                else
                {
                    model.UserID = user.ID;
                    model.Parents = user.CommandID == null ? new List<AllParent_Mod>() : um.GetUserParent(user.CommandID.Value).ToList();
                    allChild = new List<AllChild_Mod> {new AllChild_Mod
                    {
                        Uid=user.ID,
                        Balance=(double)user.Balance,
                        ChildName=user.LoginName,
                        LastLoginTime=user.LastLoginTime,
                        RegistTime=user.RegistTime,
                        Type=user.UserType,
                        OnlineState=base.OnLineUsers.ContainsKey(user.ID) ? (base.OnLineUsers[user.ID] == null ? UserOnlineState.DowLine : UserOnlineState.OnLine) : UserOnlineState.DowLine
                    } };
                    model.ChildsCount = um.GetUserChilds(model.UserID.Value).Count();
                    model.Childs = allChild;
                }
            }
            else if (model.UserID.HasValue)
            {
                model.Parents = um.GetUserParent(model.UserID.Value).ToArray();
                var page = model.PageInfo;
                int sumCount;
                allChild = um.GetUserChild(model.UserID.Value, false, (page.CurrPage - 1) * page.PageCount, page.PageCount, out sumCount, model.OrderByBalanceASC, model.OrderByRegestTimeASC, where, param.ToArray()).ToArray();
                model.PageInfo.SunCount = sumCount;
                allChild = allChild.Select(p => new AllChild_Mod
                {
                    Balance = p.Balance,
                    ChildsCount = p.ChildsCount,
                    ChildName = p.ChildName,
                    LastLoginTime = p.LastLoginTime,
                    RegistTime = p.RegistTime,
                    Uid = p.Uid,
                    Type = p.Type,
                    OnlineState = base.OnLineUsers.ContainsKey(p.Uid) ? (base.OnLineUsers[p.Uid] == null ? UserOnlineState.DowLine : UserOnlineState.OnLine) : UserOnlineState.DowLine
                });
                model.Childs = allChild;
                model.ChildsCount = um.GetUserChilds(model.UserID.Value).Count();
            }
            if (allChild == null)
            {
                int sumCount;
                var page = model.PageInfo;
                allChild = um.GetUserChild((page.CurrPage - 1) * page.PageCount, page.PageCount, out sumCount, model.OrderByBalanceASC, model.OrderByRegestTimeASC, where, param.ToArray()).ToArray();

                allChild = allChild.Select(p => new AllChild_Mod
                {
                    Balance = p.Balance,
                    ChildsCount = p.ChildsCount,
                    ChildName = p.ChildName,
                    LastLoginTime = p.LastLoginTime,
                    RegistTime = p.RegistTime,
                    Uid = p.Uid,
                    Type = p.Type,
                    OnlineState = base.OnLineUsers.ContainsKey(p.Uid) ? (base.OnLineUsers[p.Uid] == null ? UserOnlineState.DowLine : UserOnlineState.OnLine) : UserOnlineState.DowLine
                });
                model.PageInfo.SunCount = sumCount;
                model.Childs = allChild;
            }
            var temp = um.Select(s => new { AllCount = s.Count(), SurrogateCount = s.Where(p => p.UserType == (short)UserType.Surrogate).Count() });
            ViewData["AllCount"] = temp.AllCount;
            ViewData["SurrogateCount"] = temp.SurrogateCount;
            return View(model);
        }

        [HttpPost, ActionName("AllUser"), Authorize(Roles = "Manager_User_Select")]
        public ActionResult AllUser_Post([Bind(Exclude = "UserID")]AllChildModel model)
        {
            if (ModelState.IsValid)
            {
                if (model.PageInfo != null)
                    model.PageInfo.CurrPage = 1;
                return AllUser(model);
            }
            return AllUser(null);
        }
        private void GetWhere(AllChild_Where model, out string where, out List<object> param)
        {
            where = " 1==1 ";
            param = new List<object>();
            string url = "";
            if (model.StartTime != null)
            {
                where += " and RegistTime>=@" + param.Count;
                param.Add(model.StartTime.Value);
                url = "&Where.StartTime=" + model.StartTime;
            }
            if (model.EndTime != null)
            {
                where += " and RegistTime<@" + param.Count;
                param.Add(model.EndTime.Value.AddDays(1));
                url = "&Where.EndTime=" + model.EndTime;
            }
            if (model.MaxMoney != null)
            {
                where += " and Balance <=@" + param.Count;
                param.Add(model.MaxMoney);
                url = "&Where.MaxMoney=" + model.MaxMoney;
            }
            if (model.MinMoney != null)
            {
                where += " and Balance >=@" + param.Count;
                param.Add(model.MinMoney);
                url = "&Where.MinMoney=" + model.MinMoney;
            }
            ViewData["url"] = url;
        }

        #region 删除用户
        [Authorize(Roles = "Manager_User_Delete")]
        public ActionResult Delete(DeleteModel model, string msg)
        {
            if (!string.IsNullOrEmpty(msg))
                ViewData["msg"] = msg.AlertOffPage();
            if (model.DeleteType == 0)
                model.DeleteType = 2;
            return View(model);
        }

        [HttpPost, ActionName("Delete"), MultiButton(Name = "Search"), Authorize(Roles = "Manager_User_Delete")]
        public ActionResult Delete_Post(DeleteModel model)
        {
            if (model.DeleteType == 1)
            {
                if (ModelState["UserName"].Errors.Count == 0)
                {
                    var um = new UserManage();
                    var user = um.Select(s => s.Where(p => p.LoginName == model.UserName).Select(p => new User_Comm
                    {
                        Uid = p.ID,
                        CommandID = p.CommandID,
                        Commmands = p.Commands,
                        LoginName = p.LoginName,
                        RegistTime = p.RegistTime,
                        UserTye = p.UserType,
                        Money = (double)(p.Account.Balance + p.Account.FreezeMoney)
                    }).FirstOrDefault());
                    if (user == null)
                        ViewData["msg"] = "未找到指定用户";
                    else
                    {
                        model.SeachResult = new List<User_Comm> { user };
                        model.CommCommand = um.GetCommand(user.CommandID).ToList();
                    }
                }
            }
            else if (model.DeleteType == 2)
            {
                if (ModelState["StartTime"].Errors.Count == 0 && ModelState["MinMoney"].Errors.Count == 0)
                {
                    model.SeachResult = new UserManage().GetNoAccountUsers(model.StartTime, model.MinMoney).ToList();
                    var commStr = GetCommStr(model.SeachResult.Select(p => p.Commmands).ToArray(), 0);
                    if (commStr != null)
                    {
                        var index = commStr.LastIndexOf('&');
                        Guid uid = new Guid(index < 0 ? commStr : commStr.Substring(index + 1));
                        model.CommCommand = new UserManage().GetCommand(uid).ToList();
                    }
                }
            }
            return View(model);
        }

        public string GetCommStr(string[] strList, int index)
        {
            if (strList == null || strList.Length == 0)
                return null;
            var str = strList.OrderBy(p => p.Length).First();
            if (str == "")
                return null;
            index = str.IndexOf('&', index + 1);
            var result = index < 0 ? str : str.Substring(0, index);
            var flag = strList.Select(p => p.StartsWith(result)).Contains(false);

            if (flag && index == 0)
                return null;
            else if (flag || index < 0)
                return result;
            else
                return GetCommStr(strList, index);
        }

        [HttpPost, ActionName("Delete"), MultiButton(Name = "Delete"), Authorize(Roles = "Manager_User_Delete")]
        public ActionResult DeleteUser(Guid? id, short DeleteType)
        {
            var msgStr = string.Empty;
            var idsStr = Request.Form["ids"];
            if (!string.IsNullOrEmpty(idsStr))
            {
                var ids = idsStr.Split(',');
                var um = new UserManage();
                string msg;
                var count = 0;
                foreach (var idStr in ids)
                {
                    Guid uid = new Guid(idStr);
                    var i = um.DeleteUser(uid, out msg, id);
                    if (i > 0)
                        count++;
                }
                if (count == ids.Length)
                {
                    msgStr = string.Format("已成功删除{0}条", count);
                }
                else
                {
                    msgStr = string.Format("已成功删除{0}条,失败{1}条", count, ids.Length - count);
                }
            }
            return Delete(new DeleteModel { DeleteType = DeleteType }, msgStr);
        }

        #endregion

        #region 修改用户类型
        [Authorize(Roles = "Manager_User_Edit")]
        public ActionResult Chage(Guid? id)
        {
            ChageModel model = new ChageModel();
            if (id.HasValue)
            {
                var um = new UserManage();
                model.ID = id.Value;
                var user = um.Select(s => s.Where(p => p.ID == id.Value).Select(p => new User_Comm
                {
                    Uid = p.ID,
                    CommandID = p.CommandID,
                    Commmands = p.Commands,
                    LoginName = p.LoginName,
                    Money = (double)(p.Account.Balance + p.Account.FreezeMoney),
                    RegistTime = p.RegistTime,
                    UserTye = p.UserType
                }).FirstOrDefault());
                if (user == null)
                    ViewData["msg"] = "您要修改的用户未找到".AlertOffPage();
                else
                {
                    model.User = user;
                    model.Commands = um.GetCommand(user.CommandID).ToList().Select(p => new SelectListItem { Text = p.LoginName, Value = p.Uid.ToString() });
                }
            }
            return View(model);
        }
        [HttpPost, Authorize(Roles = "Manager_User_Edit")]
        public ActionResult Chage(ChageModel model)
        {
            if (model != null)
            {
                string msg;
                var count = new UserManage().UpdateUserType(model.ID, out msg, true, model.CommandID);
                if (count > 0)
                    ViewData["msg"] = "更改成功！".AlertOffPage() + Request["returnUrl"].Redirect();
                else if (msg != "")
                    ViewData["msg"] = msg.AlertOffPage();
                else
                    ViewData["msg"] = "更改失败，请稍后重新操作！";
            }
            return View(model);
        }
        [Authorize(Roles = "Manager_User_Edit")]
        public JsonResult Chage_Json(Guid id)
        {
            var msg = "";
            var count = new UserManage().UpdateUserType(id, out msg, true);
            return Json(new { count, msg }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 查看详情
        [Authorize(Roles = "Manager_User_Select,Manager_User_Edit")]
        public ActionResult Manage_Detail(Guid id)
        {
            var model = new Manage_DetailModel();
            UserOptionManage uom = new UserOptionManage();
            var userOption = uom[id, Option_User_Key.Lock_info];
            var des = new Code.Commen.DES();
            model = new UserManage().Select(s => s.Where(p => p.ID == id).Select(p => new Manage_DetailModel
            {
                Uid = p.ID.ToString(),
                Detail = new Manage_UserDetail
                {
                    LoginName = p.LoginName,
                    BankCardNo = p.Person.BankCardNo,
                    BankCityID = p.Person.BankCityID,
                    BankID = p.Person.BankID,
                    BankStreetName = p.Person.BankStreet,
                    Email = p.Person.Email,
                    Name = p.Person.Name,
                    QQ = p.Person.QQ,
                    State = p.State,
                    UserType = p.UserType,
                    Tel = p.Person.Phone,
                    PayAccount = p.Person.PayAccount,
                },
                RegestTime = p.RegistTime,
                Accout = p.Account
            }).FirstOrDefault());
            model.Detail.Locked = userOption == null ? false : userOption.ToBool(false);
            model.OldDetail = model.Detail;
            var salt = Salt.Generic.GetDesSalt();
            model.Uid = des.EncryptString(model.Uid, salt.Key, salt.Value);
            return View(model);
        }
        [HttpPost]
        [Authorize(Roles = "Manager_User_Edit")]
        public ActionResult Manage_Detail(Manage_DetailModel model)
        {
            Guid uid = new Guid();
            try
            {
                var salt = Salt.Generic.GetDesSalt();
                uid = new Guid(new Code.Commen.DES().DecryptString(model.Uid, salt.Key, salt.Value));
            }
            catch
            {
                ViewData["msg"] = "数据异常".AlertOffPage();
                return View(model);
            }
            if (ModelState.IsValid)
            {
                var keys = "Detail.LoginPwd&Detail.CheckCode&OldDetail.LoginPwd&OldDetail.CheckCode";
                var temp = false;
                if (string.IsNullOrEmpty(model.OldDetail.BankCardNo))
                    temp = true;
                else
                {
                    var data = ModelState.Where(p => !keys.Contains(p.Key));
                    temp = !data.Select(p => p.Value.Errors.Count == 0).Contains(false);
                }
                if (temp)
                {
                    var count = 0;
                    var update = new NameValue<string, object>();
                    NameValue<string, object> where;

                    if (model.Detail.Locked != model.OldDetail.Locked)
                    {
                        var uom = new UserOptionManage();
                        var i = uom.Update(uid, Option_User_Key.Lock_info, model.Detail.Locked.ToString());
                        if (i > 0)
                        {
                            count += i;
                            model.OldDetail.Locked = model.Detail.Locked;
                        }
                    }

                    var um = new UserManage();
                    //userType
                    if (model.Detail.LoginName != model.OldDetail.LoginName)
                    {
                        var flag = um.BoolLoginName(model.Detail.LoginName);
                        if (flag)
                        {
                            model.Detail.LoginName = model.OldDetail.LoginName;
                            ModelState.AddModelError("Detail.LoginName", "用户名已存在");
                        }
                        else
                            update.Add("LoginName", model.Detail.LoginName);
                    }
                    if (model.Detail.State != model.OldDetail.State)
                    {
                        if (model.OldDetail.State == (short)UserState.Freez)
                        {
                            var i = um.UserFreeMoney(uid);
                            if (i > 0)
                            {
                                count += i;
                                model.OldDetail.State = model.Detail.State;
                            }
                            update.Add("State", model.Detail.State);
                        }
                        else if (model.Detail.State == (short)UserState.Freez)
                        {
                            var i = um.UserFreezeMoney(uid, (UserState)model.OldDetail.State);
                            if (i > 0)
                            {
                                count += i;
                                model.OldDetail.State = model.Detail.State;
                            }
                        }
                        else
                            update.Add("State", model.Detail.State);
                    }
                    if (model.Detail.UserType.HasValue && model.Detail.UserType != model.OldDetail.UserType)
                    {
                        string msg;
                        count = um.UpdateUserType(uid, out msg, true);
                        if (!string.IsNullOrEmpty(msg))
                            ViewData["msg"] = msg.AlertOffPage();
                        if (count > 0)
                            model.OldDetail.UserType = model.Detail.UserType;
                    }
                    //LoginPwd
                    if ((!string.IsNullOrEmpty(model.LoginPwd)) & model.LoginPwd != "LoginPwd")
                    {
                        var i = um.EditLoginPwd(uid, model.LoginPwd);
                        if (i > 0) { count += i; ViewData["msg"] = "".Redirect("登录密码保存成功"); }
                        else ModelState.AddModelError("LoginPwd", "登录密码保存失败，请重新操作。");
                    }
                    if (update.Count > 0)
                    {
                        where = new NameValue<string, object>
                    {
                        {"ID",uid}
                    };
                        var i = um.Update(update, where);
                        if (i > 0)
                        {
                            count += update.Count;
                            model.OldDetail.LoginName = model.Detail.LoginName;
                            model.OldDetail.Name = model.Detail.Name;
                            model.OldDetail.State = model.Detail.State;
                        }
                        else
                            ViewData["msg"] = "保存失败！".AlertOffPage();
                    }

                    update = new NameValue<string, object>();
                    if (model.Detail.Tel != model.OldDetail.Tel)
                        update.Add("Phone", model.Detail.Tel);
                    if (model.Detail.QQ != model.OldDetail.QQ)
                        update.Add("QQ", model.Detail.QQ);
                    if (model.Detail.Name != model.OldDetail.Name)
                        update.Add("Name", model.Detail.Name);
                    if (model.Detail.BankStreetName != model.OldDetail.BankStreetName)
                        update.Add("BankStreet", model.Detail.BankStreetName);
                    if (model.Detail.BankID != model.OldDetail.BankID)
                        update.Add("BankID", model.Detail.BankID);
                    if (model.Detail.BankCityID != model.OldDetail.BankCityID)
                        update.Add("BankCityID", model.Detail.BankCityID);
                    if (model.Detail.PayAccount != model.OldDetail.PayAccount)
                        update.Add("PayAccount", model.Detail.PayAccount);
                    //BankCardNo
                    if (model.Detail.BankCardNo != model.OldDetail.BankCardNo)
                    {
                        if (!string.IsNullOrEmpty(model.Detail.BankCardNo) && um.Select(s => s.Where(p => p.ID != uid).Select(p => p.Person.BankCardNo).Contains(model.Detail.BankCardNo)))
                        {
                            model.Detail.BankCardNo = model.OldDetail.BankCardNo;
                            ModelState.AddModelError("Detail.BankCardNo", "该卡号已有人在使用，请重新输入。");
                        }
                        else
                        {
                            update.Add("BankCardNo", model.Detail.BankCardNo);
                        }
                    }
                    //Email
                    if (model.Detail.Email != model.OldDetail.Email)
                    {
                        var flag = string.IsNullOrEmpty(model.Detail.Email) || !um.Select(s => s.Any(p => p.ID != uid && p.Person.Email == model.Detail.Email));
                        if (!flag)
                        {
                            model.Detail.Email = model.OldDetail.Email;
                            ModelState.AddModelError("Detail.Email", "该邮箱已有人在使用，请重新输入。");
                        }
                        else
                            update.Add("Email", model.Detail.Email);
                    }
                    //TakePwd
                    if ((!string.IsNullOrEmpty(model.TakePwd)) && model.TakePwd != "TakePwd")
                    {
                        var i = um.EditTakePwd(uid, model.TakePwd);
                        if (i > 0)
                        {
                            count += i;
                            ViewData["msg"] = "提款密码保存成功".AlertOffPage() + "".Redirect();
                        }
                        else
                            ModelState.AddModelError("TakePwd", "提款密码保存失败，请重新操作。");
                    }
                    if (update.Count > 0)
                    {
                        where = new NameValue<string, object>()
                    {
                        {"UserID",uid}
                    };
                        var i = new CommenManage<Person>().Update(update, where);
                        if (i > 0)
                        {
                            count += update.Count;
                            model.OldDetail.QQ = model.Detail.QQ;
                            model.OldDetail.Tel = model.Detail.Tel;
                            model.OldDetail.BankCardNo = model.Detail.BankCardNo;
                            model.OldDetail.BankCityID = model.Detail.BankCityID;
                            model.OldDetail.BankID = model.Detail.BankID;
                            model.OldDetail.BankStreetName = model.Detail.BankStreetName;
                            model.OldDetail.Email = model.Detail.Email;
                        }
                        else
                            ViewData["msg"] = "保存失败！请稍后重新操作。".AlertOffPage();
                    }
                    if (count > 0)
                        ViewData["msg"] = "".Redirect("已成功保存!");
                }
            }
            return View(model);
        }

        [Authorize(Roles = "Manager_User_Edit")]
        public JsonResult UpdateMoney(UpdateMoneyModel model)
        {
            var count = -1;
            Guid uid = new Guid();
            try
            {
                var salt = Salt.Generic.GetDesSalt();
                uid = new Guid(new Code.Commen.DES().DecryptString(model.Uid, salt.Key, salt.Value));
            }
            catch
            {
                return Json(new { count }, JsonRequestBehavior.AllowGet);
            }
            if (ModelState.IsValid)
            {
                if (model != null)
                {
                    var update = new NameValue<string, object>();
                    var remark = string.Format("\r\nM{0},", AdminID);
                    if (model.OldBalance != model.NewBalance && model.NewBalance >= 0)
                    {
                        update.Add("Balance", model.NewBalance);
                        remark += string.Format("b:{0}>{1}", model.OldBalance, model.NewBalance);
                    }
                    if (model.OldFreezeMoney != model.NewFreezeMoney && model.NewFreezeMoney >= 0)
                    {
                        update.Add("FreezeMoney", model.NewFreezeMoney);
                        remark += string.Format("f:{0}>{1}", model.OldFreezeMoney, model.NewFreezeMoney);
                    }
                    if (update.Count > 0)
                    {
                        update.Add("Remark", new OpteratorValue(Opterator.Add, remark));
                        var where = new NameValue<string, object> { { "UserID", uid } };
                        count = new UserManage().Update<Account>(update, where);
                    }
                    else { count = 0; }
                }
            }
            return Json(new { count }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        [HttpPost]
        public ActionResult ChildView(string name)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(name))
                    return ChildView((Guid?)null);
                if (um == null)
                    um = new UserManage();
                var user = um.Select(s => s.FirstOrDefault(p => p.LoginName == name));
                if (user == null)
                {
                    ViewData["msg"] = "您查找的用户不存在".AlertOffPage();
                    return ChildView((Guid?)null);
                }
                return ChildView(user.ID);
            }
            return ChildView((Guid?)null);
        }
        UserManage um;
        public ActionResult ChildView(Guid? id)
        {
            if (um == null)
                um = new UserManage();
            var data = um.Select(s => s);
            TreeViewEntity model = null;
            if (!id.HasValue)
            {
                data = data.Where(p => p.CommandID == null);
                model = PassTreeView(null, data.ToArray().Select(p =>
                    new User_Comm
                    {
                        LoginName = p.LoginName,
                        Uid = p.ID,
                        CommandID = p.CommandID,
                        Commmands = p.Commands,
                        UserTye = p.UserType
                    }).ToArray());
            }
            else
            {
                currnetId = id.Value;
                var userParent = um.GetUserParent(id.Value).ToList();
                if (userParent == null || userParent.Count == 0)
                {
                    data = data.Where(p => p.CommandID == null);
                    ViewData["msg"] = "您查看的用户不存在。".AlertOffPage();
                }
                else
                {
                    data = data.Where(p => p.CommandID == null || p.Commands.Contains(id.ToString()));
                }
                var userlist = data.ToArray().Select(p => new User_Comm { LoginName = p.LoginName, Uid = p.ID, CommandID = p.CommandID, Commmands = p.Commands, UserTye = p.UserType }).ToList();
                userlist.AddRange(userParent.Where(p => p.CommandID != null).Select(p => new User_Comm { LoginName = p.LoginName, Uid = p.Uid, CommandID = p.CommandID, Commmands = p.Commands, UserTye = p.UserType }));
                model = PassTreeView(null, userlist);
            }

            return View(model);
        }
        private Guid currnetId;
        public TreeViewEntity PassTreeView(User_Comm user, IEnumerable<User_Comm> userList)
        {
            TreeViewEntity treeView = new TreeViewEntity();
            var list = userList;
            if (user == null)
            {
                treeView.NodeHtml = " ";
                list = userList.Where(p => p.CommandID == null);
            }
            else
            {
                var isSurrogate = user.UserTye == (short)UserType.Surrogate;
                list = userList.Where(p => p.CommandID == user.Uid);
                var nodeHtml = string.Format("{2}{0}&nbsp;&nbsp;<a href='{1}' title='转到用户管理'><font color='blue'>→</font></a>", currnetId == user.Uid ? "<font color='red'>" + user.LoginName + "</font>" : user.LoginName, Url.Action("AllUser", Url.Route(new { Where = new { ChildName = user.LoginName }, returnUrl = Url.Action("ChildView", new { id = user.Uid }) })), isSurrogate ? list.Count() == 0 ? "+" : "-" : "");
                treeView.NodeHtml = nodeHtml;
                treeView.NodeVlue = user.Uid.ToString();
                var classStr = "treeViewComm";
                if (isSurrogate)
                {
                    classStr += "  SurrogateNode";
                }
                treeView.Attributes.Add("class", classStr);
                treeView.Attributes.Add("onmouseover", "mouseover(this)");
                treeView.Attributes.Add("onmouseout", "mouseout(this)");
            }
            foreach (var item in list)
            {
                treeView.NodeList.Add(PassTreeView(item, userList));
            }
            return treeView;
        }

        [Authorize(Roles = "Manager_User_Edit")]
        public ActionResult SetAddChildConfig(PageInfo pageInfo, SetAddChildConfigModel.SerchUser serch)
        {
            var acc = new AddChildConfigManage();
            var temp = acc.Select(s => s.Where(p => p.Users.CommandID == null && p.Users.UserType == (short)UserType.Surrogate));
            if (serch != null)
            {
                if (!string.IsNullOrEmpty(serch.Name))
                    temp = temp.Where(p => p.Users.LoginName == serch.Name);
                if (serch.MaxCount_AllChild.HasValue)
                    temp = temp.Where(p => p.AllChildCount <= serch.MaxCount_AllChild.Value);
                if (serch.MinCount_AllChild.HasValue)
                    temp = temp.Where(p => p.AllChildCount >= serch.MinCount_AllChild.Value);
            }
            var data = temp.Select(p => new AddChildConfigModel
            {
                AllChildCount = p.AllChildCount,
                uid = p.Users.ID,
                UserType = p.Users.UserType,
                UserName = p.Users.LoginName
            }).ToList();
            var list = acc.Select(s => s.Where(p => s.Where(pp => pp.Users.CommandID == null && pp.Users.UserType == (short)UserType.Surrogate).Select(pp => pp.UserID).Contains(p.Users.CommandID.Value)).Select(p => new { acc = p, p.Users.CommandID, p.Users.UserType })).ToArray();
            data.Each(p =>
            {
                var tempList = list.Where(pp => pp.CommandID == p.uid);
                p.NowChildCount = p.AllChildCount - tempList.Sum(pp => pp.acc.AllChildCount) - tempList.Count();
            });
            if (serch != null)
            {
                if (serch.MaxCount.HasValue)
                    data = data.Where(p => p.NowChildCount <= serch.MaxCount).ToList();
                if (serch.MinCount.HasValue)
                    data = data.Where(p => p.NowChildCount >= serch.MinCount).ToList();
            }
            var model = new SetAddChildConfigModel();
            if (pageInfo != null)
                model.PageInfo = pageInfo;
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();
            model.PageInfo.SunCount = data.Count;
            model.UsersConfig = data.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount).OrderByDescending(p => p.AllChildCount).ToList();
            if (serch != null)
                model.Serch = serch;
            return View(model);
        }
        [Authorize(Roles = "Manager_User_Edit")]
        [HttpPost]
        public ActionResult SetAddChildConfig(SetAddChildConfigModel.SerchUser serch)
        {
            return SetAddChildConfig(null, serch);
        }
        [Authorize(Roles = "Manager_User_Edit")]
        public JsonResult UpdateAll(int? AllChildCount)
        {
            if (!ModelState.IsValid)
                return Json(new { msg = "数据有误!操作失败！", count = -1 }, JsonRequestBehavior.AllowGet);
            if (AllChildCount < 0)
                return Json(new { msg = "增量必须大于零", count = -1 }, JsonRequestBehavior.AllowGet);
            var acc = new AddChildConfigManage();
            var count = acc.UpdateAll(AllChildCount ?? 0);
            return Json(new { msg = count > 0 ? "操作成功！" : "操作失败！请稍后再试!", count }, JsonRequestBehavior.AllowGet);
        }
        [Authorize(Roles = "Manager_User_Edit")]
        public JsonResult UpdateAddChildConfig(SetAddChildConfigModel model)
        {
            if (!ModelState.IsValid)
                return Json(new { msg = "数据有误!", count = -1 }, JsonRequestBehavior.AllowGet);
            var acc = new AddChildConfigManage();
            var tempOldValue = acc.Select(s => s.FirstOrDefault(p => p.UserID == model.Uid));
            if (tempOldValue == null)
                return Json(new { msg = "当前用户未找到", count = -1 }, JsonRequestBehavior.AllowGet);
            model.OldACCValue = tempOldValue.AllChildCount;
            var tempu = acc.GetNowAddChildConfig(model.Uid);
            var accN = model.ACCValue - model.OldACCValue;
            model.ACCValue = model.OldACCValue + accN;
            accN = model.ACCValue - model.OldACCValue;
            if (accN < 0 && tempu.AllChildCount < -accN)
                return Json(new { msg = "当前用户的可用配额不足", count = -1 }, JsonRequestBehavior.AllowGet);

            var update = new NameValue<string, object>
            {
                {"AllChildCount",model.ACCValue},
                {"AllSurrogateCount",0}
            };
            var where = new NameValue<string, object>
            {
                {"UserID",model.Uid}
            };
            int count = acc.Update(update, where);
            return Json(new { msg = count > 0 ? "操作成功！" : "操作失败，请稍后再试！", count }, JsonRequestBehavior.AllowGet);
        }
        #endregion

        #region 奖金设置
        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult WinMoney(LotteryTypeType? lottery, Guid? uid)
        {

            if (uid == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }
            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == uid.Value));
            if (user == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }

            if (!lottery.HasValue && CacheManage.LotteryTypes.Count > 0)
                lottery = CacheManage.LotteryTypes.OrderBy(p => p.Value.ID).First().Key;

            var PM = new PlayTypeOptionManage();
            var models = new QianBuo.Lottery.Web.Models.User.WinMoneyModel();
            models.Uid = uid.Value;
            models.UserName = user.LoginName;
            var useroption = PM.GetWinMoneyOption(uid, (int)lottery.GetValueOrDefault(), null, false).ToArray();
            models.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            models.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);

            models.Lotterys = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Text = p.Value.Name, Value = p.Key.ToString(), Selected = p.Key == lottery }).ToList();
            models.Ratios = CacheManage.Ratio.Select(p => new SelectListItem { Text = p.Value.Name + "模式", Value = ((double)p.Value.BackMoneyDifference * 100).ToString(), Selected = p.Key == 1 }).ToList();
            models.WinModels = CacheManage.WinModel.Values.OrderBy(p => p.ID).ToNameValue(p => p.Name, p => p.ID);

            models.WinMoneys = useroption.GroupBy(p => p.PlayTypeID)
                .OrderBy(p => p.Key)
                .ToNameValue(
                    p => new NameValueItem<int, string>
                        {
                            Key = p.Key,
                            Value = CacheManage.PlayType[p.Key].PlayTypeList.Name
                        },
                    p => p.Select(pp => new WinMoneyItem
                        {
                            BadkMoneyRatio = Math.Round(pp.BackMoneyRatio * 100, 9),
                            BackMoneyToWinMoneyRatio = pp.BackMoneyToWinMoneyRatio,
                            MaxBackMoneyToWinMoney = Math.Round(pp.MaxBackMoneyToWinMoney * 100, 9),
                            WinMoney = pp.WinMoney,
                            WinModelID = pp.WinMoneyModelID,
                            PlayTypeID = pp.PlayTypeID
                        }));

            ViewData["WinMoney_LotteryType"] = lottery;
            ViewData["WinMoney_Uid"] = uid.Value;
            return View(models);
        }

        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult SetWinMoney(LotteryTypeType? id, Guid? uid)
        {
            var model = new PlayTypeOptionModel();
            var LM = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort);
            model.Lotterys = new ModelNameValue<LotteryTypeType, string>(LM.Select(p => new NameValueItem<LotteryTypeType, string>(p.Key, p.Value.Name)));
            if (uid == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }
            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == uid.Value));
            if (user == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }

            if (id.HasValue)
                model.LotteryID = id;
            else if (!id.HasValue && model.Lotterys.Count > 0)
                model.LotteryID = model.Lotterys.First().Key;
            else
                model.LotteryID = (LotteryTypeType)(-1);
            model.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            if (model.UseSiteWinMoney)
            {
                 ViewData["msg"] = "当前奖金使用站点奖金来派奖，不能更改奖金".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            }
            var PM = new PlayTypeOptionManage();
            model.Options = PM.GetUserOption_Set(user.ID, (int)model.LotteryID.Value.GetDefaultLottery(), null, true).ToArray();
            model.Uid = user.ID;
            model.UserName = user.LoginName;
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult SetWinMoney(PlayTypeOptionModel model)
        {

            if (model == null || model.Options == null)
                return RedirectToAction("PlayTypeOption");
            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == model.Uid));
            if (user == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }
            model.UserName = user.LoginName;
            model.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);

            var PM = new PlayTypeOptionManage();
            PlayTypeOptionManage.WinMoneyOptionSetItem[] old = PM.GetUserOption_Set(user.ID, (int)model.LotteryID.Value.GetDefaultLottery(), null, true).ToArray();
            if (model.Options != null)
            {

                old.Each((p, i) =>
                {
                    //如果下标有改动测用此代码
                    i = Array.FindIndex(model.Options, p1 => p1.Option.PlayTypeID == p.Option.PlayTypeID && p1.Option.WinMoneyModelID == p.Option.WinMoneyModelID);
                    var item = model.Options[i];
                    item.LotteryName = p.LotteryName;
                    item.PlayName = p.PlayName;
                    item.Option.LotteryID = p.Option.LotteryID;
                    item.Option.PlayTypeID = p.Option.PlayTypeID;
                    item.Option.PlayTypeListID = p.Option.PlayTypeListID;
                    item.Option.WinMoneyModelID = p.Option.WinMoneyModelID;
                    item.CurrentWimMoney = p.CurrentWimMoney;
                    item.CurrentBackMoneyRatio = p.CurrentBackMoneyRatio;
                    item.MaxBackMoneyRatio = p.MaxBackMoneyRatio;
                    item.MaxWinMoney = p.MaxWinMoney;
                    item.MinBackMoneyRatio = p.MinBackMoneyRatio;
                    item.MinWinMoney = p.MinWinMoney;
                    item.PlaySort = p.PlaySort;

                    if (model.UseSiteWinMoney)
                        item.Option.WinMoney = p.Option.WinMoney;
                    else
                    {
                        if (item.Option.WinMoney > item.MaxWinMoney)
                            ModelState.AddModelError(string.Format("Options[{0}].Option.WinMoney", i), "<=" + item.MaxWinMoney);
                        else if (item.Option.WinMoney < item.MinWinMoney)
                            ModelState.AddModelError(string.Format("Options[{0}].Option.WinMoney", i), ">=" + item.MinWinMoney);
                    }
                    if (model.UseSiteBackMoneyRatio)
                        item.Option.BackMoneyRatio = p.Option.BackMoneyRatio;
                    else
                    {
                        if (item.Option.BackMoneyRatio > item.MaxBackMoneyRatio)
                            ModelState.AddModelError(string.Format("Options[{0}].Option.BackMoneyRatio", i), "<=" + item.MaxBackMoneyRatio);
                        else if (item.Option.BackMoneyRatio < item.MinBackMoneyRatio)
                            ModelState.AddModelError(string.Format("Options[{0}].Option.BackMoneyRatio", i), ">=" + item.MinBackMoneyRatio);
                    }

                });
            }
            else
            {
                return Redirect(Url.Action("SetWinMoney", new { model.Uid, id = model.LotteryID }).Redirect("参数不正确！"));
            }

            if (ModelState.IsValid)
            {
                int rs = PM.SetUserOption(model.Uid, model.Options.Select(p => p.Option));
                if (rs < 0)
                    ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                else
                    ViewData["msg"] = Url.Action("SetWinMoney", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");
            }

            return View(model);
        }

        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult SubWinMoneyMargin(Guid id)
        {
            var UM = new UserManage();
            var user = UM.Select(s => s.Select(p => new { p.ID, p.LoginName }).FirstOrDefault(p => p.ID == id));
            if (user == null)
                return Content(Url.Action("AllUser").Redirect("不存在该用户！"));

            var model = new SubWinMoneyMarginModel() { ID = id, UserName = user.LoginName };
            model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
            model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
            model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
            model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            return View(model);
        }


        [Authorize(Roles = "Manager_User_WinMoney")]
        [HttpPost]
        public ActionResult SubWinMoneyMargin(SubWinMoneyMarginModel model)
        {
            if (model != null)
            {
                model.WinModels = CacheManage.WinModel.Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.WinModelID == p.Value.ID }).ToList();
                model.WinModels.Insert(0, new SelectListItem { Text = "选择模式", Value = "" });
                model.Lotters = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort).Select(p => new SelectListItem { Value = p.Key.ToString(), Text = p.Value.Name, Selected = model.Lottery == p.Key }).ToList();
                model.Lotters.Insert(0, new SelectListItem { Text = "选择彩种", Value = "" });
            }
            if (ModelState.IsValid)
            {
                LotteryType? lottery = model.Lottery.HasValue ? (model.Lottery.Value.GetDefaultLottery()) as LotteryType? : null;
                var PM = new PlayTypeOptionManage();
                int rs = PM.SetUserSubWinMoneyMargin(model.ID, model.WinModelID, lottery, model.WinMoneyRatio, model.BackMoneyRatioMargin, true);
                if (rs > 0)
                    return Content("".Redirect("调整完成！"));
                else if (rs == 0)
                    return Content("".Redirect("无操作！"));
                else
                    ViewData["msg"] = "操作失败，请稍后再试！".AlertOffPage();

            }
            return View(model);
        }


        #endregion

        #region 返点设置

        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult SetWinRatio(LotteryTypeType? id, Guid? uid)
        {
            if (uid == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }
            var user = new UserManage().Select(s => s.FirstOrDefault(p => p.ID == uid.Value));
            if (user == null)
            {
                var msg = (Request["returnurl"] ?? Url.Action("AllUser")).Redirect("您要查看的用户不存在！");
                return Content(msg);
            }
            var PM = new PlayTypeOptionManage();
           
            var model = new PlayTypeOptionModel();
            var LM = CacheManage.LotteryTypes.OrderBy(p => p.Value.Sort);
            model.Lotterys = new ModelNameValue<LotteryTypeType, string>(LM.Select(p => new NameValueItem<LotteryTypeType, string>(p.Key, p.Value.Name)));
            if (id.HasValue)
                model.LotteryID = id;
            else if (!id.HasValue && model.Lotterys.Count > 0)
                model.LotteryID = model.Lotterys.First().Key;
            else
                model.LotteryID = (LotteryTypeType)(-1);

            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            var win = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            if (model.UseSiteBackMoneyRatio &&  win==false)
            {
                ViewData["msg"] = "不能设置返点".AlertOffPage();
                ViewData["btnAddDisabled"] = true;
            }
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
            model.Uid =(Guid)uid;
            model.Options = PM.GetOptionUser_Set(uid.Value, (int)model.LotteryID.Value.GetDefaultLottery(), null, true).ToArray();
            model.WinMoneyState = Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById();
            model.Options.Each(p => p.MaxBackMoneyRatio = Math.Min(MemberMaxSetRatio, p.MaxBackMoneyRatio));
            model.UserName = user.LoginName;
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_User_WinMoney")]
        public ActionResult SetWinRatio(PlayTypeOptionModel model)
        {


            model.UseSiteWinMoney = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteWinMoney].ToBool(false);
            model.UseSiteBackMoneyRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false);
            var MemberMaxSetRatio = CacheManage.OptionSite[Option_Site_Key.Site_Lottery_Member_MaxBackMoneyRatio].ToDouble(100);
         
            PlayTypeOptionManage mana = new PlayTypeOptionManage();
            if (model.Options != null)
            {
                if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true && CacheManage.OptionSite[Option_Site_Key.Site_Lottery_UseSiteBackMoneyRatio].ToBool(false))
                {
                    int couts = 0;
                    foreach (var item in model.Options)
                    {
                        if (item.States == false)
                        {
                            couts++;
                        }
                    }

                    if (couts == model.Options.Count())
                    {
                        ViewData["msg"] = Url.Action("SetWinRatio", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                        return View(model);
                    }
                    List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                    foreach (var item in model.Options)
                    {
                        int winId = item.Option.WinMoneyModelID;
                        int num = 0;
                        foreach (var MyWinId in model.Options)
                        {
                            if (winId == MyWinId.Option.WinMoneyModelID)
                            {
                                model.Options[num].States = item.States;
                            }
                            num++;
                        }
                      
                    }
                    foreach (var item in model.Options)
                    {
                        Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                        back.BackMoneyRatio = item.Option.BackMoneyRatio;
                        back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                        back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                        var winId = item.Option.WinMoneyModelID;
                        back.States = item.States;
                        list.Add(back);
                    }
                   
                    var number = mana.Updatewin(list, mana.Name(model.Uid).LoginName);
                    if (number > 0)
                    {
                        ViewData["msg"] = Url.Action("SetWinRatio", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");
                        return View(model);
                    }
                }
                if (model.UseSiteBackMoneyRatio == false)
                {
                    List<PlayTypeOptionManage.BackMoney> list = new List<PlayTypeOptionManage.BackMoney>();
                    foreach (var item in model.Options)
                    {
                        int winId = item.Option.WinMoneyModelID;
                        int num = 0;
                        foreach (var MyWinId in model.Options)
                        {
                            if (winId == MyWinId.Option.WinMoneyModelID)
                            {
                                model.Options[num].States = item.States;
                            }
                            num++;
                        }
                    }

                    if (Code.BLL.PlayTypeOptionManage.SelectFromOption_SetById() == true)
                    {
                        int i = 0;
                        foreach (var item in model.Options)
                        {
                            if (item.States == false)
                            {
                                i++;
                            }
                        }

                        if (i == model.Options.Count())
                        {
                            ViewData["msg"] = Url.Action("SetWinRatio", new { id = model.LotteryID, uid = model.Uid }).Redirect("您设置的会员必须拥有至少一个模式！");
                            return View(model);
                        }
                        else
                        {
                            foreach (var item in model.Options)
                            {
                                Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                                back.BackMoneyRatio = item.Option.BackMoneyRatio;
                                back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                                back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                                var winId = item.Option.WinMoneyModelID;
                                back.States = item.States;
                                list.Add(back);
                            }
                        }

                        int result = mana.UpdateOption(list, model.Uid);
                        if (result < 0)
                            ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                        else
                            ViewData["msg"] = Url.Action("SetWinRatio", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");

                    }
                    else
                    {
                        foreach (var item in model.Options)
                        {
                            Code.BLL.PlayTypeOptionManage.BackMoney back = new PlayTypeOptionManage.BackMoney();
                            back.BackMoneyRatio = item.Option.BackMoneyRatio;
                            back.BackMoneyTypeId = Convert.ToInt32(item.Option.BackMoneyTypeID);
                            back.WinMoneyTypeID = item.Option.WinMoneyModelID;
                            var winId = item.Option.WinMoneyModelID;
                            back.States = true;
                            list.Add(back);
                        }
                        int update = mana.UpdateOptionUser(list, model.Uid);
                        if (update < 0)
                            ViewData["msg"] = "操作失败！请稍后重试。".AlertOffPage("msg.value = '';", false);
                        else
                            ViewData["msg"] = Url.Action("SetWinRatio", new { id = model.LotteryID, uid = model.Uid }).Redirect("保存成功！");
                    }
                }
            }
            else
            {
                return Redirect(Url.Action("SetWinRatio", new { model.Uid, id = model.LotteryID }).Redirect("参数不正确！"));
            }
            model.Options = mana.GetOptionUser_Set(model.Uid, 1, null, true).ToArray();

            model.Options.Each(p => p.MaxBackMoneyRatio = Math.Min(MemberMaxSetRatio, p.MaxBackMoneyRatio));

            return View(model);
        }
        #endregion

        #region 为用户充值
        [Authorize(Roles = "Manager_Account_AddMoney")]
        public ActionResult AddMoney()
        {
            var model = new AddMoneyModel();
            return View(model);
        }

        [HttpPost]
        [Authorize(Roles = "Manager_Account_AddMoney")]
        public ActionResult AddMoney(AddMoneyModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var AM = new AddMoneyManage();
                    int rs = AM.AdminAddMoney(model.UserName, model.Money.Value, base.AdminID);
                    if (rs > 0)
                        ViewData["msg"] = "".Redirect("充值成功");
                    else
                        ViewData["msg"] = "操作失败，请稍后再试".AlertOffPage();
                }
                catch (AppException a)
                { ModelState.AddModelError(a.Source, a.Message); }
                catch { ViewData["msg"] = "操作失败，请稍后再试".AlertOffPage(); }
            }
            return View(model);
        }

        [ActionName("TransferAccount")]
        public ActionResult TransferAccount_Get(TransferAccountModel model)
        {
            return TransferAccount(model);
        }

        [Authorize(Roles = "Manager_Account_AddMoney")]
        [HttpPost, MultiButton(Name = "SerchTransferAccount")]
        public ActionResult TransferAccount(TransferAccountModel model)
        {
            if (model == null)
                model = new TransferAccountModel();
            if (model.Serch == null)
                model.Serch = new TransferAccountSerchModel();
            if (!model.Page.HasValue || model.Page < 1)
                model.Page = 1;
            if (!model.PageSize.HasValue || model.PageSize < 1)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(10);

            double tmp;
            model.ChargeRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_ChargeRatio].ToDouble(out tmp) ? tmp : null as double?;
            model.MinRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MinCharge].ToDouble(out tmp) ? tmp : null as double?;
            model.MaxRatio = CacheManage.OptionSite[Option_Site_Key.Site_Pay_ICBC_Manual_MaxCharge].ToDouble(out tmp) ? tmp : null as double?;

            var AM = new AddMoneyManage();
            var data = AM.Select<PayDetail, IQueryable<PayDetail>>(s => s);
            var tp = data.Select(p => new TransferAccountItem { ID = p.ID, OrderID = p.OrderID, Result = (PayResult)p.Result, AddTime = p.AddTime, Money = (double)p.Money, SuccesTime = p.SuccesTime, UserID = p.UserID, UserName = p.Users.LoginName, Admin = p.Remark, SiteID = p.SiteID });
            if (model.Serch.Order.HasValue)
            {
                tp = tp.Where(p => p.OrderID == model.Serch.Order);
                model.Serch.Result = null;
            }
            if (model.Serch.Result.HasValue)
                tp = tp.Where(p => p.Result == model.Serch.Result);
            if (!string.IsNullOrEmpty(model.Serch.UserName))
                tp = tp.Where(p => p.UserName == model.Serch.UserName);
            if (model.Serch.StartTime.HasValue)
                tp = tp.Where(p => p.AddTime >= model.Serch.StartTime);
            if (model.Serch.EndTime.HasValue)
                tp = tp.Where(p => p.AddTime < model.Serch.EndTime.Value.AddDays(1));
            if (!string.IsNullOrEmpty(model.Serch.SiteID))
                tp = tp.Where(p => p.SiteID == model.Serch.SiteID);

            var ms = AM.Select<Admin, IEnumerable<Admin>>(s => s.ToArray()).Select(p => new { ID = p.ID.ToString(), p.LoginName });

            model.SumCount = tp.Count();
            model.Datas = tp.OrderByDescending(p => p.AddTime).Skip(model.PageSize.Value * (model.Page.Value - 1)).Take(model.PageSize.Value).ToArray()
                .Each(p => { var t = ms.FirstOrDefault(p1 => p1.ID == p.Admin); if (t == null) p.Admin = ""; else p.Admin = t.LoginName; });
            model.Results = (Enum.GetValues(typeof(PayResult)) as PayResult[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString(), Selected = p == model.Serch.Result }).ToList();
            model.Results.Insert(0, new SelectListItem { Text = "选择", Value = "", Selected = model.Serch.Result.HasValue });
            return View(model);
        }


        [Authorize(Roles = "Manager_Account_AddMoney")]
        [ActionName("TransferAccount")]
        [HttpPost, MultiButton(Name = "ConfirmTransferAccount")]
        public ActionResult ConfirmTransferAccount(TransferAccountModel model)
        {
            if (!model.OrderID.HasValue)
            {
                ModelState.AddModelError("OrderID", "请输入正确的订单号");
            }
            else
            {

                var AM = new AddMoneyManage();
                var pay = AM.Select<PayDetail, PayDetail>(s => s.FirstOrDefault(p => p.OrderID == model.OrderID.Value));
                if (pay == null)
                {
                    ModelState.AddModelError("OrderID", "不存在该订单，请确认输入无误。");
                }
                else if (pay.Result != (short)PayResult.WatingPay)
                {
                    ModelState.AddModelError("OrderID", "订单已为:" + ((PayResult)pay.Result).GetName());
                }
                else
                {
                    pay.Remark = AdminID.ToString();
                    int rs = AM.CallBackPay(pay);
                    if (rs < 0)
                        ViewData["msg"] = "操作失败，请稍后再试".AlertOffPage();
                    else
                    {
                        ViewData["msg"] = "确认转账成功".AlertOffPage(); ;
                        model.Serch.Order = model.OrderID;

                    }
                }
            }
            return TransferAccount(model);
        }

        [Authorize(Roles = "Manager_Account_AddMoney")]
        [ActionName("TransferAccount")]
        [HttpPost, MultiButton(Name = "RevocationTransferAccount")]
        public ActionResult RevocationTransferAccount(TransferAccountModel model)
        {
            if (!model.OrderID.HasValue)
            {
                ModelState.AddModelError("OrderID", "请输入正确的订单号");
            }
            else
            {

                var AM = new AddMoneyManage();
                var pay = AM.Select<PayDetail, PayDetail>(s => s.FirstOrDefault(p => p.OrderID == model.OrderID.Value));
                if (pay == null)
                {
                    ModelState.AddModelError("OrderID", "不存在该订单，请确认输入无误。");
                }
                else if (pay.Result != (short)PayResult.WatingPay)
                {
                    ModelState.AddModelError("OrderID", "订单已为:" + ((PayResult)pay.Result).GetName());
                }
                else
                {
                    pay.Remark = AdminID.ToString();
                    int rs = AM.RevocationOrder(pay);
                    if (rs < 0)
                        ViewData["msg"] = "操作失败，请稍后再试".AlertOffPage();
                    else
                    {
                        ViewData["msg"] = "确认撤销成功".AlertOffPage(); ;
                        model.Serch.Order = model.OrderID;

                    }
                }
            }
            return TransferAccount(model);
        }
        #endregion

        #region 团队账变
        [Authorize(Roles = "Manager_Account_Report")]
        public ActionResult AccountDetail(DetailModel model)
        {
            if (model == null)
                model = new DetailModel();
            if (model.Serch == null)
                model.Serch = new UserManage.UserAccountDetailSerch();
            model.Types = (Enum.GetValues(typeof(UserAccountDetailType)) as UserAccountDetailType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.Types.Insert(0, new SelectListItem { Text = "所有明细", Value = string.Empty });
            model.UserTypes = (Enum.GetValues(typeof(UserType)) as UserType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.UserTypes.Insert(0, new SelectListItem { Text = "所有组", Value = string.Empty });

            UserManage UM = new UserManage();
            if (ModelState.IsValid)
            {
                if (model.PageSize <= 0)
                    model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(15); ;
                if (!model.Page.HasValue)
                    model.Page = 1;

                if (model.uid.HasValue)
                {
                    var user = UM.Select(s => s.FirstOrDefault(p => p.ID == model.uid));
                    if (user == null)
                        ViewData["msg"] = "用户不存在".AlertOffPage();
                    else if (user.UserType != (short)UserType.Surrogate)
                        ViewData["msg"] = "用户不是代理".AlertOffPage();
                }

                var report = UM.GetUserAccountDetail(model.Serch, null, model.uid);
                if (model.Serch != null && model.Serch.Type.HasValue && model.Serch.Type == UserAccountDetailType.WinMoney)
                {
                    report = report.Join(UM.Select<Scheme, IEnumerable<Scheme>>(s => s), p => p.ID, p => p.ID.ToString(), (p1, p2) => new UserAccountDetail
                    {
                        AddTime = p1.AddTime,
                        CommandID = p1.CommandID,
                        Commands = p1.Commands,
                        ID = p1.ID,
                        InMoney = p1.InMoney,
                        LoginName = p1.LoginName,
                        Memo = p1.Memo,
                        Money = p1.Money,
                        OutMoney = (double)p2.SchemeMoney,
                        State = p1.State,
                        Type = p1.Type,
                        UserID = p1.UserID,
                        UserType = p1.UserType
                    });
                }
                if (!string.IsNullOrEmpty(model.OrderByName))
                {
                    report = report.OrderBy(model.OrderByName + " " + (string.IsNullOrEmpty(model.OrderByType) ? "" : model.OrderByType.Equals("ASC", StringComparison.CurrentCultureIgnoreCase) || model.OrderByType.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? model.OrderByType : ""));
                }
                else
                    report = report.OrderByDescending(p => p.AddTime);
                if (model.uid.HasValue)
                    report = report.Where(p => p.UserID != model.uid.Value);

                var reg = new Regex(@"^\w{1,}:[-0-9]{1,}期", RegexOptions.Compiled);
                var u = UM.Select<Users, Account>(s => s.Where(p => p.LoginName == model.Serch.LoginName).Select(p => p.Account).FirstOrDefault());
                var issubmoney = (u != null && !model.Serch.Type.HasValue && !model.Serch.MaxMoney.HasValue && !model.Serch.MinMoney.HasValue);
                double money = 0;
                if (issubmoney)
                {
                    money = Math.Round((double)u.Balance, 4);
                    var m = UM.GetUserAccountDetail(new UserManage.UserAccountDetailSerch { LoginName = model.Serch.LoginName, StartTime = (model.Serch.EndTime ?? DateTime.Now).Date.AddDays(1) }, u.UserID).Where(p => p.Memo == null || !p.Memo.Contains("(已付)")).Sum(p => (double?)(p.InMoney ?? 0) + (-p.OutMoney ?? 0)) ?? 0;
                    m += report.Take(model.PageSize * (model.Page.Value - 1)).Where(p => p.Memo == null || !p.Memo.Contains("(已付)")).Sum(p => (double?)(p.InMoney ?? 0) + (-p.OutMoney ?? 0)) ?? 0;
                    money = Math.Round(money - m, 4);
                }

                model.SumCount = report.Count();
                if (model.SumCount > 0)
                {

                    model.SumDetail = report.GroupBy(p => 1).Select(p => new QianBuo.Lottery.Web.Models.Account.AccountDetail { InMoney = p.Sum(pp => pp.InMoney), OutMoney = p.Sum(pp => pp.OutMoney) }).FirstOrDefault() ?? new QianBuo.Lottery.Web.Models.Account.AccountDetail();
                    model.Details = report.Skip(model.PageSize * (model.Page.Value - 1)).Take(model.PageSize)
                        .Select(p => new QianBuo.Lottery.Web.Models.Account.AccountDetail { LoginName = p.LoginName, UserID = p.UserID, UserType = p.UserType, ID = p.ID, AddTime = p.AddTime, Memo = p.Memo, State = p.State, InMoney = p.InMoney, OutMoney = p.OutMoney, Type = (UserAccountDetailType)p.Type }).ToList();
                    model.Details.Each(p =>
                    {
                        if (issubmoney)
                        {
                            p.Money = money;
                            if (string.IsNullOrEmpty(p.Memo) || !p.Memo.Contains("(已付)"))
                                money = money + (-p.InMoney ?? 0) + (p.OutMoney ?? 0);
                        }
                        int? state; int tp;
                        state = int.TryParse(p.State, out tp) ? tp as int? : null;
                        if ((p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.Other) && p.ID != null && (p.Info = p.ID.Split('&').Select(pp => { var nv = pp.Split(':'); return new { N = nv[0], V = nv[1] }; }).ToDictionary(pp => pp.N, pp => pp.V)).Count > 0)
                            p.ID = p.Info.ContainsKey("RefID") ? p.Info["RefID"] : null;

                        if (p.Type == UserAccountDetailType.AddMoney) p.StateText = ((AddMoneyType)state).GetName();
                        if (p.Type == UserAccountDetailType.BackMoney_Child || p.Type == UserAccountDetailType.WinMoney_Child || p.Type == UserAccountDetailType.Play ||
                            p.Type == UserAccountDetailType.WinMoney || p.Type == UserAccountDetailType.QuashScheme || p.Type == UserAccountDetailType.BackMoney ||
                            (p.Type == UserAccountDetailType.Other && state == (short)OtherMoneyDetailType.BackTimeOutScheme))
                        {
                            if (reg.IsMatch(p.Memo ?? string.Empty))
                            {
                                int i1 = p.Memo.IndexOf(":");
                                int i2 = p.Memo.IndexOf("期");
                                var str = p.Memo.Substring(0, i1);
                                LotteryType l = (LotteryType)int.Parse(str);
                                str = p.Memo.Substring(i1 + 1, i2 - i1 - 1);
                                var str1 = Issue.PastIssueName(l, str);
                                p.Memo = string.Format("{0}:{1}{2}", l.GetName(), str1, p.Memo.Substring(i2));
                            }
                        }
                        if (p.Type == UserAccountDetailType.Other && state.HasValue) { p.StateText = ((OtherMoneyDetailType)state).GetName(); }
                        if (p.Type == UserAccountDetailType.ChaseTask && state.HasValue) { p.StateText = ((ChaseTaskState)state).GetName(); p.Memo = ((LotteryType)int.Parse(p.Memo)).GetName() + "追号任务"; }
                        if (p.Type == UserAccountDetailType.Freez && state.HasValue) { p.StateText = ((FreezeMoneyDetailState)state).GetName(); p.Memo = ((FreezeCause)int.Parse(p.Memo)).GetName(); }
                    });
                    if (issubmoney && model.Page * model.PageSize >= model.SumCount)
                        model.Details.Add(new Web.Models.Account.AccountDetail { AddTime = model.Serch.StartTime, LoginName = model.Serch.LoginName, Money = money, Memo = "结转之前的余额" });
                }
                else if (issubmoney)
                {
                    model.Details = new List<Web.Models.Account.AccountDetail>();
                    model.SumDetail = new Web.Models.Account.AccountDetail();
                    model.Details.Add(new Web.Models.Account.AccountDetail { AddTime = model.Serch.StartTime, LoginName = model.Serch.LoginName, Money = money, Memo = "结转之前的余额" });
                }
            }

            return View(model);
        }
        #endregion

        #region 团队报表
        [Authorize(Roles = "Manager_Account_Report")]
        public ActionResult AccountReport(QianBuo.Lottery.Web.Models.Surrogate.AccountReportModel model)
        {
            if (model.PageSize <= 0)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(20);
            if (model.Page <= 0)
                model.Page = 1;
            model.UserTypes = (Enum.GetValues(typeof(UserType)) as UserType[]).Select(p => new SelectListItem { Text = p.GetName(), Value = p.ToString() }).ToList();
            model.UserTypes.Insert(0, new SelectListItem { Text = "所有组", Value = string.Empty });

            var UM = new UserManage();
            if (model.uid.HasValue)
            {
                var user = UM.Select(s => s.FirstOrDefault(p => p.ID == model.uid));
                if (user == null)
                    ViewData["msg"] = "用户不存在".AlertOffPage();
                else if (user.UserType != (short)UserType.Surrogate)
                    ViewData["msg"] = "用户不是代理".AlertOffPage();
            }
            model.MinSerchTime = (UM.Select<UserAccountDetail, UserAccountDetail>(s => s.OrderBy(p => p.AddTime).FirstOrDefault()) ?? new UserAccountDetail { AddTime = DateTime.Now }).AddTime;
            model.MaxSerchTime = DateTime.Now;

            var report = UM.GetUserAccountReport(model.Serch, null, model.uid);
            if (model.uid.HasValue)
                report = report.Where(p => p.UserID != model.uid.Value);
            var rs = report.GroupBy(p => new { p.UserID, p.LoginName, p.UserType })
                .Select(p => new AccountReport
                {
                    LoginName = p.Key.LoginName,
                    UserID = p.Key.UserID,
                    UserType = p.Key.UserType,
                    AddMoney = p.Sum(pp => pp.SumAddMoney),
                    TackMoney = p.Sum(pp => pp.SumTackMoney),
                    PlayMoney = p.Sum(pp => pp.SumPlayMoney),
                    BackMoney = p.Sum(pp => pp.SumBackMoney),
                    BackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                    WinMoney = p.Sum(pp => pp.SumWinMoney),
                    WinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                });

            model.SumCount = rs.Count();

            if (model.SumCount > 0)
            {
                model.SumReport = report.GroupBy(p => 1).Select(p => new AccountReport
                {
                    AddMoney = p.Sum(pp => pp.SumAddMoney),
                    TackMoney = p.Sum(pp => pp.SumTackMoney),
                    PlayMoney = p.Sum(pp => pp.SumPlayMoney),
                    BackMoney = p.Sum(pp => pp.SumBackMoney),
                    BackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                    WinMoney = p.Sum(pp => pp.SumWinMoney),
                    WinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                }).First();
                model.Reports = rs.OrderByDescending(p => p.LoginName).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize).ToArray();
            }

            return View(model);
        }

        [Authorize(Roles = "Manager_Account_Report")]
        public ActionResult AccountReportDetail(ReportModel model)
        {
            if (model.Page < 1)
                model.Page = 1;
            if (model.PageSize < 1)
                model.PageSize = CacheManage.OptionSite[Option_Site_Key.Site_PageInfo_PageCount].ToInt32(20);

            var UM = new UserManage();
            if (!string.IsNullOrEmpty(model.Serch.LoginName))
            {
                var user = UM.Select(s => s.Any(p => p.LoginName == model.Serch.LoginName));
                if (!user)
                    ModelState.AddModelError("Serch.LoginName", "不存在该用户！");
            }
            else
            {
                ModelState.AddModelError("Serch.LoginName", "用户名不能为空");
            }

            if (ModelState.IsValid)
            {

                var accounts = UM.GetUserAccountReport(model.Serch, null);
                accounts = accounts.Where(p => p.LoginName == model.Serch.LoginName);
                model.Account = UM.Select<Account, Account>(s => s.FirstOrDefault(p => p.Users.LoginName == model.Serch.LoginName));
                model.MimSerchEndTime = (UM.Select<UserAccountDetail, UserAccountDetail>(s => s.OrderBy(p => p.AddTime).FirstOrDefault()) ?? new UserAccountDetail { AddTime = DateTime.Now.Date }).AddTime;
                model.SumCount = accounts.Count();
                if (model.SumCount > 0)
                {
                    model.SumReport = accounts.GroupBy(p => 1).Select(p => new QianBuo.Lottery.Web.Models.Account.AccountReportModel
                    {
                        SumAddMoney = p.Sum(pp => pp.SumAddMoney),
                        SumPlayMoney = p.Sum(pp => pp.SumPlayMoney),
                        SumTackMoney = p.Sum(pp => pp.SumTackMoney),
                        SumBackMoney = p.Sum(pp => pp.SumBackMoney),
                        SumBackMoney_Child = p.Sum(pp => pp.SumBackMoney_Child),
                        SumWinMoney = p.Sum(pp => pp.SumWinMoney),
                        SumWinMoney_Child = p.Sum(pp => pp.SumWinMoney_Child)
                    }).First();
                    model.Reports = accounts.OrderByDescending(p => p.Year).OrderByDescending(p => p.Month).OrderByDescending(p => p.Day)
                        .Select(p => new QianBuo.Lottery.Web.Models.Account.AccountReportModel
                        {
                            Year = p.Year,
                            Month = p.Month,
                            Day = p.Day,
                            SumAddMoney = p.SumAddMoney,
                            SumPlayMoney = p.SumPlayMoney,
                            SumTackMoney = p.SumTackMoney,
                            SumBackMoney = p.SumBackMoney,
                            SumBackMoney_Child = p.SumBackMoney_Child,
                            SumWinMoney = p.SumWinMoney,
                            SumWinMoney_Child = p.SumWinMoney_Child
                        }).Skip(model.PageSize * (model.Page - 1)).Take(model.PageSize).ToArray();
                    model.Reports.Each(p => { p.Date = new DateTime(p.Year, p.Month, p.Day); });
                }
            }
            else
            {
                return RedirectToAction("AccountReport");
            }
            return View(model);
        }
        #endregion

        #region 团队余额
        [Authorize(Roles = "Manager_Account_Report")]
        public ActionResult GroupMoney(GroupMoneyModel model)
        {
            if (model.PageInfo == null)
                model.PageInfo = new PageInfo();
            var um = new UserManage();
            var IsSurrogate = true;
            model.CurrentUserCommands = new Dictionary<Key<Guid, Guid?>, string>();
            if (!string.IsNullOrEmpty(model.UserName))
            {
                var user = um.Select(s => s.FirstOrDefault(p => p.LoginName == model.UserName.Trim()));
                if (user == null)
                {
                    ViewData["msg"] = "没有您要查找的用户".AlertOffPage();
                }
                else
                {
                    model.CurrenUid = user.ID;
                    IsSurrogate = user.UserType == (short)UserType.Surrogate;
                }
            }
            else if (model.CurrenUid.HasValue)
            {
                var user = um.Select(s => s.FirstOrDefault(p => p.ID == model.CurrenUid));
                if (user == null)
                {
                    ViewData["msg"] = "没有您要查找的用户".AlertOffPage();
                }
                else
                {
                    IsSurrogate = user.UserType == (short)UserType.Surrogate;
                }
            }


            if (model.CurrenUid.HasValue)
            {

                model.CurrentUserCommands = um.GetUserParent(model.CurrenUid.Value).ToDictionary(p => new Key<Guid, Guid?>(p.Uid, p.CommandID), p => p.LoginName);
            }
            if (IsSurrogate || model.CurrenUid == null)
            {
                var data = um.Select(s => s);
                if (model.CurrenUid.HasValue)
                    data = data.Where(p => p.Commands.Contains(model.CurrenUid.ToString()));
                //整个团队账户统计
                var allSumData = data.GroupBy(p => 1).Select(p => new GroupMoneyModel.AccountDetail
                {
                    Balance = (double)p.Sum(p1 => p1.Account.Balance),
                    Freez = (double)p.Sum(p1 => p1.Account.FreezeMoney),
                    AddMoney = (double)p.Sum(p1 => p1.Account.AddMoney),
                    BackMoney = (double)p.Sum(p1 => p1.Account.BackMoney),
                    BackMoney_Child = (double)p.Sum(p1 => p1.Account.BackMoney_Child),
                    Buy = (double)p.Sum(p1 => p1.Account.BuyLottery),
                    TackMoney = (double)p.Sum(p1 => p1.Account.TackMoney),
                    WinMoney = (double)p.Sum(p1 => p1.Account.WinMoney),
                    WinMoney_Child = (double)p.Sum(p1 => p1.Account.WinMoney_Child)
                }).FirstOrDefault();
                if (allSumData == null)
                    allSumData = new GroupMoneyModel.AccountDetail();
                else if (model.StartTime.HasValue || model.EndTime.HasValue)
                {
                    var temp = um.Select<UserAccountReport, IEnumerable<UserAccountReport>>(s => s);
                    if (model.CurrenUid.HasValue)
                        temp = temp.Where(p => p.Commands.Contains(model.CurrenUid.ToString()));
                    if (model.StartTime.HasValue)
                        temp = temp.Where(p => p.Date >= model.StartTime.Value.Date);
                    if (model.EndTime.HasValue)
                        temp = temp.Where(p => p.Date <= model.EndTime.Value.Date);
                    temp = temp.GroupBy(p => 1).FirstOrDefault();
                    allSumData = new GroupMoneyModel.AccountDetail
                    {
                        Balance = allSumData.Balance,
                        Freez = allSumData.Freez,
                        AddMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumAddMoney),
                        BackMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumBackMoney),
                        BackMoney_Child = temp == null ? 0d : (double)temp.Sum(p => p.SumBackMoney_Child),
                        Buy = temp == null ? 0d : (double)temp.Sum(p => p.SumPlayMoney),
                        TackMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumTackMoney),
                        WinMoney = temp == null ? 0d : (double)temp.Sum(p => p.SumWinMoney),
                        WinMoney_Child = temp == null ? 0d : (double)temp.Sum(p => p.SumWinMoney_Child)
                    };
                }
                model.AllChildsAccountSum = allSumData;
            }
            var allUser = um.Select(s => s.Where(p => p.CommandID == null));
            if (!string.IsNullOrEmpty(model.UserName))
                allUser = um.Select(s => s.Where(p => p.ID == model.CurrenUid));
            else if (model.CurrenUid.HasValue)
                allUser = um.Select(s => s.Where(p => p.Commands.EndsWith(model.CurrenUid.ToString())));

            model.PageInfo.SunCount = allUser.Count();
            if (model.StartTime.HasValue || model.EndTime.HasValue)
            {
                var str = "";
                var ps = new List<object>();
                if (model.StartTime.HasValue)
                {
                    str = " Date>=@" + ps.Count;
                    ps.Add(model.StartTime.Value.Date);
                }
                if (model.EndTime.HasValue)
                {
                    str += (ps.Count == 1 ? " And " : "") + " Date<=@" + ps.Count;
                    ps.Add(model.EndTime.Value.Date);
                }
                var temp = um.Select<UserAccountReport, IEnumerable<UserAccountReport>>(s => s.Where(str, ps.ToArray()));
                model.ChildAccountDetail = allUser.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount)
                   .GroupJoin(temp, p => p.ID, p => p.UserID, (p1, p2) => new { user = p1, uar = p2 })
                    .ToDictionary(p => p.user.ID, p => new GroupMoneyModel.AccountDetail
                    {
                        LoginName = p.user.LoginName,
                        UserType = p.user.UserType,
                        Balance = (double)p.user.Account.Balance,
                        Freez = (double)p.user.Account.FreezeMoney,
                        AddMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumAddMoney),
                        BackMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumBackMoney),
                        BackMoney_Child = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumBackMoney_Child),
                        Buy = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumPlayMoney),
                        TackMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumTackMoney),
                        WinMoney = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumWinMoney),
                        WinMoney_Child = (double)p.uar.DefaultIfEmpty(new UserAccountReport()).Sum(pp => pp.SumWinMoney_Child)
                    });
            }
            else
            {
                model.ChildAccountDetail = allUser.Skip((model.PageInfo.CurrPage - 1) * model.PageInfo.PageCount).Take(model.PageInfo.PageCount)
                    .ToDictionary(p => p.ID, p => new GroupMoneyModel.AccountDetail
                    {
                        LoginName = p.LoginName,
                        UserType = p.UserType,
                        Balance = (double)p.Account.Balance,
                        Freez = (double)p.Account.FreezeMoney,
                        AddMoney = (double)p.Account.AddMoney,
                        BackMoney = (double)p.Account.BackMoney,
                        BackMoney_Child = (double)p.Account.BackMoney_Child,
                        Buy = (double)p.Account.BuyLottery,
                        TackMoney = (double)p.Account.TackMoney,
                        WinMoney = (double)p.Account.WinMoney,
                        WinMoney_Child = (double)p.Account.WinMoney_Child
                    });
            }
            return View(model);
        }
        #endregion

        #region 登录前台用户
        [Authorize(Roles = "Manage_User_Login")]
        public ActionResult Login(string userName)
        {
            if (!string.IsNullOrEmpty(userName))
            {
                CommenManage<Users> cm = new CommenManage<Users>();
                var u = cm.Select(s => s.Where(p => p.LoginName == userName).Select(p => new { p.ID, p.UserType, p.Account.Balance, p.Account.FreezeMoney, p.State }).FirstOrDefault());
                if (u == null)
                {
                    ModelState.AddModelError("userName", "没有找到当前用户");
                    return View();
                }

                var aus = System.Configuration.ConfigurationManager.GetSection("system.web/authentication") as System.Web.Configuration.AuthenticationSection;
                if (aus != null)
                {
                    OnLineManagers.Remove(AdminID);
                    FormsAuthentication.SignOut();
                    var winModel = CacheManage.WinModel.FirstOrDefault(p => p.Value.State == (short)WinMoneyModelState.Normal);
                    var radio = CacheManage.Ratio.FirstOrDefault(p => p.Value.State == (short)ConsumeRatioState.Normal);
                    var str = string.Format("LoginID:{0}&WinModel:{1}&Ratio:{2}&Roles:{5},User{3}&Them:{4}", u.ID, winModel.Value.ID, (double)radio.Value.Ratio, u.UserType == (short)UserType.Surrogate ? ",Surrogate" : "", "", AuthorityKey.Manage_User_Login.ToString());
                    FormsAuthenticationTicket tick = new FormsAuthenticationTicket(2, str, DateTime.Now, DateTime.Now.AddMinutes(aus.Forms.Timeout.TotalMinutes), false, "");
                    HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tick));
                    if (Response.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName))
                        Response.Cookies.Set(cookie);
                    else
                        Response.Cookies.Add(cookie);
                    Session["Login_Uid"] = u.ID;
                }
                return RedirectToAction("Index", "Home", new { area = "" });
            }
            return View();
        }
        #endregion
    }
}
